<template>
  <!-- authentication.js里加了大屏的鉴权，这段在服务器渲染，样式会被过滤掉，一片白，加了 q-no-ssr 解决 -->
  <q-no-ssr>
    <div class="data-view" :style="cssVars">
      <div id="full-screen-container" class="full-screen-container">
        <div class="child-container">
          <router-view ref="child" />
        </div>
      </div>
    </div>
  </q-no-ssr>
</template>

<script>
import { defineComponent, ref } from 'vue';
import { useMeta, LocalStorage } from 'quasar';
import { useStore } from 'stores/store';
import { mapState, mapActions } from 'pinia';
import autofit from 'src/lib/autofit.js';
import io from 'socket.io-client';
import EventBus from 'src/lib/event-bus'; // 用于组件间通信
import { browserInfo, osInfo } from '../lib/ClientInformation';

export default defineComponent({
  setup (props, context) {
    const $store = useStore();
    useMeta({
      // 设置文件标题
      title: `${$store.siteConfig.appName} - 木多鱼系列`,
      meta: {
        description: {
          name: 'description',
          content: $store.siteConfig.description || $store.siteConfig.subTitle
        }
      }
    });
  },
  beforeRouteEnter (to, from, next) { // 前置路由守卫
    // 检测权限
    let { rights } = LocalStorage.getItem('user');

    if (rights && typeof rights === 'string') {
      rights = JSON.parse(rights);
    }

    const subPath = to.path.split('/')[2];

    if (rights && rights[subPath] && rights[subPath].func) {
      next();
    } else {
      next('/404');
    }
  },
  data () {
    return {
      userInfo: { user: {}, role: {}, tenant: {} },
      theme: 'default' // 主题名
    }
  },
  async mounted () {
    await this.refreshUserInfo();

    setInterval(() => {
      this.adder++; // 4小时整页刷新
    }, 10 * 60 * 1000);

    this.$nextTick(() => {
      autofit.init({
        designHeight: 1080,
        designWidth: 1920,
        renderDom: '#full-screen-container',
        resize: true
      });
    });

    // 初始化socket
    this.initSocket({
      id: this.userInfo.user.id,
      nickname: this.userInfo.user.nickname,
      tid: this.userInfo.tenant.id,
      browser: `${browserInfo().browser} ${browserInfo().ver}`,
      os: osInfo()
    });
  },
  unmounted () {
    autofit.off();
  },
  provide () {
    return {
      setTheme: this.setTheme,
      getThemeName: this.getThemeName
    }
  },
  methods: {
    setTheme (name) {
      const lawNames = ['default', 'blue'];
      let themeName = 'default';
      if (lawNames.includes(name)) {
        themeName = name;
      }
      this.theme = themeName;
    },
    getThemeName () {
      return this.theme;
    },
    // 刷新登录用户信息
    async refreshUserInfo () {
      const { user, role, tenant } = (await this.$axios.get('/c/system/getUserInfo')).data;
      this.userInfo = { user, role, tenant };

      // 被禁用，退出登录
      if (!user.state || !tenant.state) {
        this.exit();
        return false;
      }

      this.$q.localStorage.set('user', user);
      this.$q.localStorage.set('role', role);
      this.$q.localStorage.set('tenant', tenant);

      if (!user.headimg) {
        this.userInfo.user.headimg = this.defaultHeadImg;
      }
    },
    exit () {
      const tenant = this.$q.localStorage.getItem('tenant_login');
      this.$q.localStorage.clear();
      this.$q.localStorage.set('tenant_login', tenant);
      window.location.replace('/tLogin');
    },
    async initSocket (user) {
      this.socket = io();

      this.socket.on('connect', () => {
        this.socket.emit('login', user); // 发送登录
      });

      this.socket.on('broadcast', async (data) => {
        console.log('broadcast', data);
        EventBus.emit(data.type, data.message);
      });
    }
  },
  computed: {
    ...mapState(useStore, ['siteInfo', 'defaultHeadImg']),
    year () {
      return (new Date()).getFullYear();
    },
    cssVars () {
      return {
        '--theme-bg': `url('/cockpit-themes/${this.theme}/bg.png')`
      }
    }
  },
  watch: {
    adder (val) {
      if (val >= 4 * 6) { // 4小时整页刷新
        this.adder = 0;
        window.location.reload();
      }
    }
  }
});
</script>

<style lang="scss">
.data-view {
  width: 100%;
  height: 100%;
  background-color: #030409;
  color: #fff;
  font-size: 14px;

  .full-screen-container {
    background-image: var(--theme-bg);
    background-size: 100% 100%;
    box-shadow: 0 0 3px blue;
    display: flex;
    flex-direction: column;
  }
  .child-container {
    flex: 1;
    display: flex;
    // flex-direction: column;
  }

  .bottom-footer {
    text-align: center;
    padding: 5px;
  }
}

.cell-wrap {
  white-space: normal!important;
  word-break: break-all!important;
}
</style>
